<?php

namespace app\api\controller;

use think\Controller as Controller;
use app\common\logic\UserLogic as UserLogic;
use app\common\logic\Oauth2 as Oauth2;
use app\common\logic\SmsLogic as SmsLogic;

class Login extends Controller {

    protected $smsLogic;
    protected $userLogic;
    protected $auth;
    protected $resDatas;
    protected $resError;
    protected $oauth2;

    public function _initialize() {
        $this->smsLogic = new SmsLogic();
        $this->userLogic = new UserLogic();
        $this->oauth2 = new Oauth2();
        $this->resDatas = [
            'msg' => '获取数据成功!',
            'code' => 1,
            'status' => 'success',
            'datas' => []
        ];
        $this->resError = [
            'msg' => '数据获取失败',
            'code' => 0,
            'status' => 'error',
            'datas' => [],
        ];
        header('Access-Control-Allow-Origin: *');
        if (request()->method() == 'OPTIONS') {
            $this->resError['msg'] = '预加载';
            return $this->resError;
        }
    }

    public function index() {
        $request = request();

        if ($request->isPost()) {
            $post = $request->post();

            $mobile = $post['m'];
            $shortcode = $post['smscode'];

            $userhas = $this->userLogic->checkUserHas($mobile);
            if($userhas->status==6){
                $this->resError['msg'] = '您已被禁止登录!';
                return $this->resError;
            }
            if ($userhas) {
                $isLogin = $this->smsLogic->checkSmsHas($userhas->id, $shortcode);

                if ($isLogin) {
                    if (smsHasOverTime($isLogin->created_at)) {
                        $this->resError['msg'] = '验证码已过期, 请重新获取';
                        $this->smsLogic->delHasSms($isLogin->id);
                        return $this->resError;
                    }

                    $clientData = array(
                        'user_id' => $userhas->id,
                        'client_id' => $mobile,
                        'client_secret' => $shortcode,
                        'redirect_uri' => ''
                    );

                    $checkclientHas = $this->oauth2->checkClientHas($mobile, $shortcode);

                    if ($checkclientHas) {
                        $clientadded = $checkclientHas;
                    } else {
                        $clientadded = $this->oauth2->addClient($clientData);
                    }

                    if ($clientadded) {
                        $authcodeData = array(
                            'user_id' => $clientadded->user_id,
                            'client_id' => $clientadded->client_id,
                            'response_type' => 'code',
                            'redirect_uri' => ''
                        );

                        $authcoded = $this->oauth2->finishClientAuthorization(TRUE, $authcodeData);

                        if ($authcoded) {
                            $tokenData = array(
                                'grant_type' => 'authorization_code',
                                'user_id' => $clientadded->user_id,
                                'client_id' => $clientadded->client_id,
                                'code' => $authcoded,
                                'client_secret' => $shortcode,
                                'redirect_uri' => '',
                                'scope' => NULL
                            );

                            $this->userLogic->exeLog([
                                'user_id' => $clientadded->user_id,
                                'login_time' => date("Y-m-d H:i:s")
                            ]);

                            $userOrg = $this->userLogic->checkUserOrg($clientadded->user_id);
                            $token = $this->oauth2->grantAccessToken($tokenData);
                            if ($userOrg) {
                                $token['group_id'] = $userOrg->group_id;
                                $token['role_id'] = $userOrg->role_id;
                                $token['isOuth']=true;
                                if($token['role_id']==2){
                                    if($token['group_id']==1){//医院
                                            if($userhas->status!=2) $token['isOuth']=false;
                                    };
                                    if($token['group_id']==3){//维修师
                                        if($userhas->status==0 || $userhas->status==2 || $userhas->status==7) $token['isOuth']=false;
                                    };
                                }

                                $token['org_name'] = $userOrg->org_id ? getOrgNameById($userOrg->user_id) : "";

                                $token['nickname'] = $userhas->nickname;
                                if (strlen($userhas->headimg)) {
                                    $token['headimg'] = config('http') . $request->server('HTTP_HOST') . $userhas->headimg;
                                } else {
                                    $token['headimg'] = $userhas->headimg;
                                }
                                $this->smsLogic->delHasSms($isLogin->id);
                            }

                            $this->resDatas['datas'] = $token;
                        }
                    }

                    return $this->resDatas;
                }

                $this->resError['msg'] = '请输入有效验证码!';
            }

            return $this->resError;
        } else {
            $this->errorDoRedirectUriCallback('', 'invalid_client', NULL, NULL, NULL);
        }
    }

    public function getverfirycode($m = 0) {
        $request = request();

        $search = '/^(1(([35][0-9])|(47)|[8][0-9]))\d{8}$/';
        if (!preg_match($search, $m)) {
            $this->resDatas['msg'] = '手机号码不正确!';
            $this->resDatas['status'] = 'fail';
            return $this->resDatas;
        }

        if (cookie('smssendok')) {
            $this->resDatas['msg'] = '请60秒后,点击发送短信!';
            $this->resDatas['code'] = 0;
            $this->resDatas['status'] = 'fail';
            return $this->resDatas;
        }

        $userhas = $this->userLogic->checkUserHas($m);

        if (!$userhas) {
            $userhas = $this->userLogic->addNoAuth2(array('mobile' => $m));
        }

        if ($userhas) {

            $verCode = rand(100000, 999999);
            $data = [
                'user_id' => $userhas->id,
                'send_type' => 1,
                'send_to' => $userhas->mobile,
                'shortcode' => $verCode
            ];
            $sms = $this->smsLogic->addSms($data);

            if ($sms) {
//                  认证短信
                $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL
                $smsConf = array(
                    'key' => 'e024ba5badef109ce732494c54278d97', //您申请的APPKEY
                    'mobile' => $sms->send_to, //接受短信的用户手机号码
                    'tpl_id' => '16597', //您申请的短信模板ID，根据实际情况修改
                    'tpl_value' => '#code#=' . $sms->shortcode //您设置的模板变量，根据实际情况修改
                );
                $respon1 = juhecurl($sendUrl, $smsConf, 1); //请求发送短信

                if ($respon1) {
                    $result = json_decode($respon1, true);
                    $error_code = $result['error_code'];
                    if ($error_code == 0) {
                        $this->resDatas['msg'] = '发送短信成功!';
                        $this->resDatas['datas'] = '验证码发送成功';
                        cookie('smssendok', '发送短信成功', 60);
                    } else {
                        $this->resDatas['msg'] = '发送短信失败!';
                        $this->resDatas['code'] = 0;
                        $this->resDatas['status'] = 'fail';
                    }
                } else {
                    $this->resDatas['msg'] = '发送短信失败!';
                    $this->resDatas['status'] = 'fail';
                    $this->resDatas['code'] = 0;
                }
            }
        }

        return $this->resDatas;
    }

    private function buildUri($uri, $params) {
        $parse_url = parse_url($uri);

        // Add our params to the parsed uri
        foreach ($params as $k => $v) {
            if (isset($parse_url[$k]))
                $parse_url[$k] .= "&" . http_build_query($v);
            else
                $parse_url[$k] = http_build_query($v);
        }

        // Put humpty dumpty back together
        return
                ((isset($parse_url["scheme"])) ? $parse_url["scheme"] . "://" : "")
                . ((isset($parse_url["user"])) ? $parse_url["user"] . ((isset($parse_url["pass"])) ? ":" . $parse_url["pass"] : "") . "@" : "")
                . ((isset($parse_url["host"])) ? $parse_url["host"] : "")
                . ((isset($parse_url["port"])) ? ":" . $parse_url["port"] : "")
                . ((isset($parse_url["path"])) ? $parse_url["path"] : "")
                . ((isset($parse_url["query"])) ? "?" . $parse_url["query"] : "")
                . ((isset($parse_url["fragment"])) ? "#" . $parse_url["fragment"] : "");
    }

    private function errorDoRedirectUriCallback($redirect_uri, $error, $error_description = NULL, $error_uri = NULL, $state = NULL) {
        $result["query"]["error"] = $error;

        if ($state)
            $result["query"]["state"] = $state;

        if ($this->getVariable('display_error') && $error_description)
            $result["query"]["error_description"] = $error_description;

        if ($this->getVariable('display_error') && $error_uri)
            $result["query"]["error_uri"] = $error_uri;

        $this->doRedirectUriCallback($redirect_uri, $result);
    }

    private function doRedirectUriCallback($redirect_uri, $params) {
        header("HTTP/1.1 " . $redirect_uri . "404 Not Found " . $params['query']['error']);
//        header("Location: " . $this->buildUri($redirect_uri, $params));
        exit;
    }

    private function getVariable($name, $default = NULL) {
        return isset($this->conf[$name]) ? $this->conf[$name] : $default;
    }

    public function test() {
        $request = request();
        return $request->header('Authorization');
    }

}
